#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

#define N 128

int main(int argc, char const *argv[])
{
    //创建TCP套接字
    int sockfd;
    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
    {
        perror("fail to socket");
        exit(-1);
    }

    //与服务器建立连接
    struct sockaddr_in server_addr;
    socklen_t addrlen = sizeof(server_addr);
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));
    if(connect(sockfd,(struct sockaddr*)&server_addr,addrlen) == -1)
    {
        perror("fail to connect");
        exit(-1);
    }
    while(1)
    {
        //发送tcp数据
        char buf_send[N] = "";
        fgets(buf_send,N,stdin);
        buf_send[strlen(buf_send)-1] = '\0';
        if(strcmp(buf_send,"exit") == 0)
            break;
        if(send(sockfd,buf_send,N,0) == -1)
        {
            perror("fail to send");
            exit(-1);
        }

        //接收tcp数据
        char buf_recv[N] = "";
        if(recv(sockfd,buf_recv,N,0) == -1)
        {
            perror("fail to recv");
            exit(-1);
        }
        printf("from server:%s\n",buf_recv);
    }

    //关闭套接字
    close(sockfd);
    return 0;
}
